<?php


namespace Ke\Log\Log4php;

use Logger;
use Exception;

trait LoggableTrait
{

	/**
	 * 过滤静态类的 logger name
	 *
	 * @param string|null $name
	 * @return string
	 */
	public static function filterStaticLoggerName(string $name = null): string
	{
		$name = $name ?? '';
		if (!empty($name) && strpos($name, '\\') !== false) {
			$name = trim($name, '\\');
			$name = str_replace('\\', '.', $name);
		}
		return $name;
	}

	/**
	 * 获取静态类的默认的 logger name
	 *
	 * @return string
	 */
	public static function getStaticDefaultLoggerName(): string
	{
		return get_called_class();
	}

	/**
	 * 获取静态类的 Logger
	 *
	 * @param string|null $name
	 * @return Logger
	 */
	public static function getStaticLogger(string $name = null)
	{
		$name = empty($name) ? static::getStaticDefaultLoggerName() : $name;
		return Logger::getLogger(static::filterStaticLoggerName($name));
	}

	/**
	 * 获取实例类的 Logger 默认名称
	 *
	 * @return string
	 */
	public function getDefaultLoggerName(): string
	{
		return get_class($this);
	}

	public function filterLoggerName(string $name): string
	{
		return static::filterStaticLoggerName($name);
	}

	/**
	 * 获取实例类的 Logger
	 *
	 * @param string|null $name
	 * @return Logger
	 */
	public function getLogger(string $name = null)
	{
		$name = empty($name) ? $this->getDefaultLoggerName() : $name;
		return Logger::getLogger($this->filterLoggerName($name));
	}

	// @see https://logging.apache.org/log4php/quickstart.html

	/**
	 * @param string         $message
	 * @param null|Exception $throwable
	 * @return $this
	 */
	public function trace($message, $throwable = null)
	{
		$this->getLogger()->trace($message, $throwable);
		return $this;
	}

	/**
	 * @param string         $message
	 * @param null|Exception $throwable
	 * @return $this
	 */
	public function debug($message, $throwable = null)
	{
		$this->getLogger()->debug($message, $throwable);
		return $this;
	}

	/**
	 * @param string         $message
	 * @param null|Exception $throwable
	 * @return $this
	 */
	public function info($message, $throwable = null)
	{
		$this->getLogger()->info($message, $throwable);
		return $this;
	}

	/**
	 * @param string         $message
	 * @param null|Exception $throwable
	 * @return $this
	 */
	public function warn($message, $throwable = null)
	{
		$this->getLogger()->warn($message, $throwable);
		return $this;
	}

	/**
	 * @param string         $message
	 * @param null|Exception $throwable
	 * @return $this
	 */
	public function error($message, $throwable = null)
	{
		$this->getLogger()->error($message, $throwable);
		return $this;
	}

	/**
	 * @param string         $message
	 * @param null|Exception $throwable
	 * @return $this
	 */
	public function fatal($message, $throwable = null)
	{
		$this->getLogger()->fatal($message, $throwable);
		return $this;
	}
}